package com.cropdoctor.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cropdoctor.common.CustomException;
import com.cropdoctor.common.EsMsgHandler;
import com.cropdoctor.common.Result;
import com.cropdoctor.mapper.NoteMapper;
import com.cropdoctor.mapper.RemindMapper;
import com.cropdoctor.mapper.VegeFruGardenMapper;
import com.cropdoctor.mapper.VegeFruTableMapper;
import com.cropdoctor.model.dto.*;
import com.cropdoctor.model.po.RemindPo;
import com.cropdoctor.model.po.VegeFruGardenPo;
import com.cropdoctor.model.po.VegeFrutablePo;
import com.cropdoctor.model.vo.VegeFruGardenVO;
import com.cropdoctor.service.VegeFruGardenService;
import com.cropdoctor.util.ContextGet;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class VegeFruGardenServiceImpl implements VegeFruGardenService {
    @Autowired
    VegeFruGardenMapper vegeFruGardenMapper;

    @Autowired
    VegeFruTableMapper vegeFruTableMapper;

    @Autowired
    NoteMapper noteMapper;

    @Autowired
    RemindMapper remindMapper;

//    @Autowired
//    RestHighLevelClient client;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result<VegeFruGardenDto> addUserVegAndFruGarden(Long idItself,String name) throws IOException {

        VegeFrutablePo vegeFrutablePo = vegeFruTableMapper.selectById(idItself);

        //若用户添加的果蔬信息查询结果为空,抛出CustomException异常
        if (vegeFrutablePo == null) throw new CustomException("用户添加的果蔬信息查询失败！");

        VegeFruGardenDto fruVegeGardenDto = new VegeFruGardenDto();

        //构造果蔬花园实体类
        VegeFruGardenPo vegeFruGardenPo = VegeFruGardenPo.builder()
                .idUser(ContextGet.getUserId())
                .mt(vegeFrutablePo.getMt())
                .st(vegeFrutablePo.getSt())
                .idTable(vegeFrutablePo.getId())
                .name(name)
                .url(vegeFrutablePo.getUrl())
                .build();

        //将构造好的果蔬实体类插入到果蔬花园中
        int result = vegeFruGardenMapper.insert(vegeFruGardenPo);

        //若插入没有成功，抛出CustomException异常
        if (result <= 0){
            throw new CustomException("果蔬花园数据插入失败");
        }

        //构造返回实体类
        BeanUtils.copyProperties(vegeFrutablePo,fruVegeGardenDto);
        return Result.success(fruVegeGardenDto);
    }

    @Override
    @Transactional
    public Result<String> deleteByGardenId(Long id) {
        VegeFruGardenPo vegeFruGardenPo = vegeFruGardenMapper.selectById(id);
        long dbIdUser = vegeFruGardenPo.getIdUser();
        long seuUserId = ContextGet.getUserId();
        if (dbIdUser != seuUserId) throw new CustomException("只能删除自己花园里的植物！");
        //根据id删除果蔬花园表中的数据
        int resultGarden = vegeFruGardenMapper.deleteById(id);

        //根据id删除关联数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("id_garden",id);
        remindMapper.deleteByMap(map);
        noteMapper.deleteByMap(map);

        //如果删除失败，抛出CustomException异常
        if (resultGarden <= 0){
            throw new CustomException("果蔬花园数据删除失败");
        }

        return Result.success("删除成功");
    }


    @Override
    public Result<List<VegeFruGardenDto>> getAll(Long userId) {
        LambdaQueryWrapper<VegeFruGardenPo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(VegeFruGardenPo::getIdUser,userId);
        List<VegeFruGardenPo> list = vegeFruGardenMapper.selectList(lambdaQueryWrapper);
        ArrayList<VegeFruGardenDto> vegeFruGardenDtos = new ArrayList<>();
        list.forEach(item ->{
            VegeFruGardenDto vegeFruGardenDto = new VegeFruGardenDto();
            BeanUtils.copyProperties(item,vegeFruGardenDto);
            vegeFruGardenDtos.add(vegeFruGardenDto);
        });
        return Result.success(vegeFruGardenDtos);
    }

    @Override
    public Result<SingleVegeFruDetailDto> getSingle(Long userId, int id) {
        VegeFruGardenPo vegeFruGardenPo = vegeFruGardenMapper.selectById(id);
        //若查询不到数据，抛出CustomException异常
        if(vegeFruGardenPo == null) throw new CustomException("查询果蔬详细信息失败!");
        long idVegeFru = vegeFruGardenPo.getIdTable();

        VegeFrutablePo vegeFrutablePo = vegeFruTableMapper.selectById(idVegeFru);
        //若查询不到数据，抛出CustomException异常
        if (vegeFrutablePo == null) throw new CustomException("查询果蔬表信息失败！");

        SingleVegeFruDetailDto singleVegeFruDetailDto = new SingleVegeFruDetailDto();
        BeanUtils.copyProperties(vegeFrutablePo,singleVegeFruDetailDto);
        singleVegeFruDetailDto.setIdGarden(vegeFruGardenPo.getId());
        singleVegeFruDetailDto.setIdUser(ContextGet.getUserId());
        singleVegeFruDetailDto.setName(vegeFruGardenPo.getName());
        singleVegeFruDetailDto.setAlias(vegeFrutablePo.getName());//用果蔬原本的名字充当别名

        return Result.success(singleVegeFruDetailDto);
    }

    @Override
    public Result<String> changeRemindList(RemindPo remindPo) {
        redisTemplate.opsForHash().put("remind_"+remindPo.getIdGarden(),remindPo.getCreateDate(),remindPo.getContentJsonArray());
        return Result.success("保存成功");
    }


    @Override
    public Result<RemindPo> getRemind(int idGarden, LocalDate date) {
        Object o = redisTemplate.opsForHash().get("remind_" + idGarden, date);
        String json = o != null ? o.toString() : "";
        RemindPo remindPo = new RemindPo();
        remindPo.setContentJsonArray(json);
        return Result.success(remindPo);
    }
}
